using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using AutoBackupSql.Models;
using FluentFTP;

namespace AutoBackupSql.Services
{
    public class FileTransferService
    {
        private readonly ILogger<FileTransferService> _logger;
        private readonly BackupSettings _settings;
        private readonly AsyncFtpClient _ftpClient;

        public FileTransferService(
            ILogger<FileTransferService> logger,
            IOptions<BackupSettings> settings)
        {
            _logger = logger;
            _settings = settings.Value;

            _ftpClient = new AsyncFtpClient(
                _settings.TargetServer.Host,
                _settings.TargetServer.Username,
                _settings.TargetServer.Password
            );
            _ftpClient.Port = _settings.TargetServer.Port;
        }

        public async Task<bool> TransferFileAsync(string sourcePath, string targetPath)
        {
            try
            {
                if (!_ftpClient.IsConnected)
                {
                    await _ftpClient.Connect();
                }

                _logger.LogInformation($"开始传输文件: {sourcePath} -> {targetPath}");

                // 确保目标目录存在
                var targetDir = Path.GetDirectoryName(targetPath);
                if (!await _ftpClient.DirectoryExists(targetDir))
                {
                    await _ftpClient.CreateDirectory(targetDir);
                }

                // 上传文件
                var status = await _ftpClient.UploadFile(sourcePath, targetPath, FtpRemoteExists.Overwrite);
                if (status == FtpStatus.Success)
                {
                    _logger.LogInformation($"文件传输完成: {targetPath}");
                    return true;
                }
                else
                {
                    _logger.LogError($"文件上传失败，状态: {status}");
                    return false;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"文件传输失败: {ex.Message}");
                return false;
            }
        }

        public async Task<bool> TestConnectionAsync()
        {
            try
            {
                if (!_ftpClient.IsConnected)
                {
                    await _ftpClient.Connect();
                }

                // 测试目录访问权限
                var testDir = Path.Combine(_settings.TargetServer.BackupPath, "test");
                if (!await _ftpClient.DirectoryExists(testDir))
                {
                    await _ftpClient.CreateDirectory(testDir);
                }

                // 测试文件写入权限
                var testFile = Path.Combine(testDir, "test.txt");
                using (var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes("test")))
                {
                    var status = await _ftpClient.UploadStream(stream, testFile);
                    if (status != FtpStatus.Success)
                    {
                        throw new Exception($"测试文件上传失败，状态: {status}");
                    }
                }

                // 清理测试文件
                if (await _ftpClient.FileExists(testFile))
                {
                    await _ftpClient.DeleteFile(testFile);
                }

                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"连接测试失败: {ex.Message}");
                return false;
            }
        }

        public async Task<bool> FileExistsAsync(string filePath)
        {
            try
            {
                if (!_ftpClient.IsConnected)
                {
                    await _ftpClient.Connect();
                }

                return await _ftpClient.FileExists(filePath);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"检查文件存在失败: {ex.Message}");
                return false;
            }
        }

        public void Dispose()
        {
            if (_ftpClient != null)
            {
                if (_ftpClient.IsConnected)
                {
                    _ftpClient.Disconnect();
                }
                _ftpClient.Dispose();
            }
        }
    }
} 